const { Service } = require('egg');

class RoomService extends Service {
  // 获取数据库中所有的酒店数据
  async getRoomList() {
    try {
      // console.log('经历了服务层');
      const RoomList = await this.app.model.HotelRoom.findAll();
      return RoomList;
    } catch (error) {
      // 获取失败
      return error;
    }
  }
  // 添加房间
  async addRoom(data) {
    try {
      // 先判断房间编号是否重复
      const selectRoom = await this.app.model.HotelRoom.findOne({
        where: {
          room_id: data.room_id,
        },
      });
      // console.log(selectRoom);
      if (selectRoom) {
        this.ctx.body = {
          code: 500,
          msg: '房间编号已存在，请重新设置',
        };
        return;
      }
      const RoomList = await this.app.model.HotelRoom.create(data);
      return RoomList;

    } catch (error) {

      return error;
    }
  }
  // 通过房间编号查询房间信息
  async getRoomById(id) {
    try {
      // console.log('经历了服务层');
      const roomById = await this.app.model.HotelRoom.findAll({
        where: {
          room_id: id,
        },
      });
      // console.log(roomById);
      return roomById;
    } catch (error) {
      // 获取失败
      return error;
    }
  }
  // 通过房间编号修改信息
  async updateRoomInfo(roomId, data) {
    try {
      // console.log('经历了服务层');
      const roomInfo = await this.app.model.HotelRoom.findOne({
        where: {
          room_id: roomId,
        },
      });
      const updateRel = await roomInfo.update(data);
      return updateRel;
    } catch (error) {
      // 获取失败
      return error;
    }
  }
  // 通过房间编号删除信息
  async delRoomInfo(roomId) {

    const result = await this.app.model.HotelRoom.findOne({
      where: {
        room_id: roomId,
      },
    });
    if (result) {
      await result.destroy();
    }
    return true;
  }
  // 按照房间价格升序排列
  async sortRoomPrice() {
    try {
      const sortPrice = await this.app.model.HotelRoom.findAll({
        order: [[ 'room_price', 'ASC' ]],
      });
      return sortPrice;
    } catch (error) {
      return error;
    }
  }
  // 降序排列
  async sortRoomPriceByDesc() {

    try {
      const sortPrice = await this.app.model.HotelRoom.findAll({
        order: [[ 'room_price', 'DESC' ]],
      });
      return sortPrice;
    } catch (error) {
      return error;
    }

  }
  // 通过酒店id查找其对应的所有房间信息
  async getRoomHotelById(hotelId) {
    try {
      // console.log('经历了服务层');
      const roomByHotelId = await this.app.model.HotelRoom.findAll({
        where: {
          hotel_id: hotelId,
        },
      });
      // console.log(roomById);
      return roomByHotelId;
    } catch (error) {
      this.ctx.logger.error(error);
      this.ctx.body = {
        code: error.code || 500,
        message: error.message || '服务器错误',
      };
    }
  }
}
module.exports = RoomService;
